<?php
    // +----------------------------------------------------------------------
    // | Created by PHPstorm: JRKAdmin框架 [ JRKAdmin ] 
    // +----------------------------------------------------------------------
    // | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
    // +----------------------------------------------------------------------
    // | SiteUrl: http://www.luckyhhy.cn
    // +----------------------------------------------------------------------
    // | Author: LuckyHhy <jackhhy520@qq.com>
    // +----------------------------------------------------------------------
    // | Date: 2020/3/12-10:04
    // +----------------------------------------------------------------------
    // | Description:  
    // +----------------------------------------------------------------------

    use \Firebase\JWT\JWT;
    use think\facade\Log;

    /**
     * @return \think\response\Json
     * @throws Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/12
     * @name: ajaxReturn
     * @describe:向前端返回JSON数据
     */
    function ajaxReturn() {
        // 形参个数
        $args_num = func_num_args();
        // 形参列表
        $args = func_get_args();
        if (1 === $args_num) {
            return json([
                'errno' => ERRNO['OK'],
                'msg'   => '成功',
                'data'  => $args[0]]);
        }
        if (2 === $args_num) {
            return json([
                'errno' => $args[0],
                'msg'   => $args[1]]);
        }
        if (3 === $args_num) {
            return json([
                'errno' => $args[0],
                'msg'   => $args[1],
                'data'  => $args[2]]);
        }
        throw new Exception("Error The number of parameters can be one or two or three");
    }


    /**
     * @param $data
     * @return JWT|string
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/12
     * @name: setJWT
     * @describe:设置JWT
     */
    function setJWT($data) {
        $jwt   = new JWT();
        $token = array(
            // "iss"  => "http://example.org", // 签发者
            // "aud"  => "http://example.com", // 认证者
            'iat'  => time(), // 签发时间
            'nbf'  => time(), // 生效时间
            'exp'  => (time() + 60 * 60 * 24 * 7), // 过期时间  7天后的时间戳
            'data' => $data,
        );
        $jwt = $jwt::encode($token, \config('jwt_key'), 'HS256');
        return $jwt;
    }

    /**
     * @param $token
     * @return array|null
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/12
     * @name: getJWT
     * @describe:获取JWT内容
     */
    function getJWT($token) {
        $jwt  = new JWT();
        $data = null;
        try {
            $jwt_data = $jwt::decode($token, \config('jwt_key'), array('HS256'));
            $data     = (array) ($jwt_data->data);
        } catch (\Throwable $e) {
            Log::write($e->getMessage(), 'error');
            return null;
        }
        return $data;
    }